package fr.waitandsee.fragments;

import fr.waitandsee.FragmentController;
import fr.waitandsee.R;
import fr.waitandsee.customwidgets.pulltorefresh.PullToRefreshBase;
import fr.waitandsee.customwidgets.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import fr.waitandsee.customwidgets.pulltorefresh.PullToRefreshScrollView;
import fr.waitandsee.tools.BitmapFactoryAdapter;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TextView;

public class HomeFragment extends Fragment implements PageFragmentModel {
	
	private static final String TAG = "HomeFragment";
	
	private PullToRefreshScrollView prsvContent;
	private ImageView ivSend;
	private ImageView ivContacts;
	private TableLayout tlReceived;
	private TableLayout tlSent;
	private TextView tvSms;
	private TextView tvFacebook;
	
	private FragmentController fragmentController;
	private Handler handler;
	
	
	public static HomeFragment newInstance(/*parameters*/) {
		HomeFragment fragment = new HomeFragment();
		// set parameters if needed : 
	    // Bundle bundle = new Bundle(1);
	    // bundle.putInt(EXTRA_NAME, param);
	    // fragment.setArguments(bundle);
	    return fragment ;
	}
	
	
	  /////////////////////////
	 // FRAGMENT LIFE CYCLE //
	/////////////////////////
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate.savedInstanceState="+savedInstanceState);
		this.fragmentController = (FragmentController) getActivity();
		this.handler = new Handler();
	}
	
 	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 		Log.d(TAG, "onCreateView.savedInstanceState="+savedInstanceState);
		if (savedInstanceState != null) {
			// get saved parameters if needed : 
			// param = savedInstanceState.getInt(EXTRA_NAME);
		} else {
			if(getArguments() != null) {
				// get parameters if needed :
				// param = getArguments().getInt(EXTRA_NAME);
			}
		}
		View v = inflater.inflate(R.layout.fragment_home, container, false);
		return v;
	}
	
 	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
 		Log.d(TAG, "onViewCreated.savedInstanceState="+savedInstanceState);
		fetchViews();
		customizeViews();
		setListeners();
	}
 	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		Log.d(TAG, "onSaveInstanceState.outState="+outState);
		super.onSaveInstanceState(outState);
		// save parameters if needed :
		// outState.putInt(EXTRA_NAME, param);
	}
 	
	@Override
 	public void fetchViews() {
		this.prsvContent = (PullToRefreshScrollView) getView().findViewById(R.id.pullRefreshScrollView_content_home);
		this.ivSend = (ImageView) getView().findViewById(R.id.imageView_head_send);
		this.ivContacts = (ImageView) getView().findViewById(R.id.imageView_head_contact);
 		this.tlReceived = (TableLayout) getView().findViewById(R.id.tableLayout_received);
 		this.tlSent = (TableLayout) getView().findViewById(R.id.tableLayout_sent);
 		this.tvSms = (TextView) getView().findViewById(R.id.textView_sms_invitation);
 		this.tvFacebook = (TextView) getView().findViewById(R.id.textView_fb_invitation);
 	}
	
	@Override
	public void customizeViews() {
		tlReceived.setScrollContainer(false);
		tlSent.setScrollContainer(false);
		
		//TODO add rows for "received media" table view
		// simulate rows in "received media" table :
		tlReceived.addView(createRowForMedia(new MediaRow(123154, "Anthony", R.drawable.ic_launcher, false, "10/01/14-14:17", "13/01/14-12:54"))); 	//DEBUG
		tlReceived.addView(createSeparator());
		tlReceived.addView(createRowForMedia(new MediaRow(465541, "Pauline", R.drawable.ic_launcher, false, "10/01/14-14:17", "13/01/14-12:54")));	//DEBUG
		tlReceived.addView(createSeparator());
		tlReceived.addView(createRowForMedia(new MediaRow(245454, "Emma", R.drawable.ic_launcher, false, "10/01/14-14:17", "13/01/14-12:54")));		//DEBUG
		
		//TODO add rows for "sent media" table view
		// simulate rows in "received media" table :
		tlSent.addView(createRowForMedia(new MediaRow(546545, "Tibal", R.drawable.ic_launcher, false, "12/01/14-15:30", "13/01/14-07:12")));		//DEBUG
		tlSent.addView(createSeparator());
		tlSent.addView(createRowForMedia(new MediaRow(846512, "Vanessa", R.drawable.ic_launcher, false, "18/01/14-23:30", "25/01/14-12:08")));	//DEBUG
	}
 	
	@Override
	public void setListeners() {
		this.prsvContent.setOnRefreshListener(onContentRefreshListener);
		this.ivSend.setOnClickListener(onSendClickListener);
		this.ivContacts.setOnClickListener(onContactsClickListener);
		this.tvSms.setOnTouchListener(onSmsTouchListener);
		this.tvFacebook.setOnTouchListener(onFacebookTouchListener);
 	}
	
	
	  ///////////////
	 // LISTENERS //
	///////////////

	private OnRefreshListener<ScrollView> onContentRefreshListener = new OnRefreshListener<ScrollView>() {
		@Override
		public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
			Log.i(TAG, "onContentRefreshListener");
			new RefreshTask().execute();
		}
	};
 	
 	private OnClickListener onSendClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.i(TAG, "onSendClickListener");
			fragmentController.switchContent(SenderFragment.newInstance());
		}
	};
	
 	private OnClickListener onContactsClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.i(TAG, "onContactsClickListener");
			fragmentController.switchContent(ContactPickerFragment.newInstance());
		}
	};
	
	private OnTouchListener onSmsTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			Log.i(TAG, "onSmsTouchListener");
			tvSms.setOnTouchListener(null); // stand-by listener to prevent multi openning
			handler.postDelayed(delayAfterTouchCallback, 200); // re-set on touch listener after 200ms
			//TODO action on "sms" textview touched
			return false;
		}
 	};
	
	private OnTouchListener onFacebookTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			Log.i(TAG, "onFacebookTouchListener");
			tvFacebook.setOnTouchListener(null); // stand-by listener to prevent multi openning
			handler.postDelayed(delayAfterTouchCallback, 200); // re-set on touch listener after 200ms
			//TODO action on "facebook" textview touched
			return false;
		}
 	};
 	
 	private Runnable delayAfterTouchCallback = new Runnable() {
 		@Override 
 		public void run() {
 			tvFacebook.setOnTouchListener(onFacebookTouchListener);
 			tvSms.setOnTouchListener(onSmsTouchListener);
 		}
 	};
 	
 	private OnClickListener onRowClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
 			Log.i(TAG, "onRowClickListener");
 			//TODO action on "row" view clicked
		}
 	};
 	
 	
 	  /////////////////
 	 // INNER CLASS //
 	/////////////////
 	
	private class MediaRow {
		public int id;
		public String name;
		public int iconRes;
		public boolean checked;
		public String sendDate;
		public String openingDate;
		public MediaRow(int id, String name, int iconRes, boolean checked, String sendDate, String openingDate) {
			this.id = id;
			this.name = name;
			this.iconRes = iconRes;
			this.checked = checked;
			this.sendDate = sendDate;
			this.openingDate = openingDate;
		}
	}
 	
	private View createRowForMedia(MediaRow mediaRow) {
		// inflate row layout
		LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View row = inflater.inflate(R.layout.row_media, null);
		// fetch row views
		ImageView ivIcon = (ImageView) row.findViewById(R.id.imageView_row);
		TextView tvName = (TextView) row.findViewById(R.id.textView_media_name);
		CheckBox cbMedia = (CheckBox) row.findViewById(R.id.checkBox_media);
		TextView tvSendDate = (TextView) row.findViewById(R.id.textView_send_date);
		TextView tvOpeningDate = (TextView) row.findViewById(R.id.textView_opening_date);
		// change views id to prevent multiple views with same id (e.g. listener)
		row.setId(row.getId()+mediaRow.id);
		ivIcon.setId(ivIcon.getId()+mediaRow.id);
		tvName.setId(tvName.getId()+mediaRow.id);
		cbMedia.setId(cbMedia.getId()+mediaRow.id);
		tvSendDate.setId(tvSendDate.getId()+mediaRow.id);
		tvOpeningDate.setId(tvOpeningDate.getId()+mediaRow.id);
		// fill row views
		ivIcon.setImageBitmap(BitmapFactoryAdapter.decodeResource(getActivity(), mediaRow.iconRes));
		tvName.setText(mediaRow.name);
		cbMedia.setChecked(mediaRow.checked);
		tvSendDate.setText(mediaRow.sendDate);
		tvOpeningDate.setText(mediaRow.openingDate);
		// set listeners
		row.setOnClickListener(onRowClickListener);
		return row;
	}
	
	private View createSeparator() {
		LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View separator = inflater.inflate(R.layout.layout_separator, null);
		return separator;
	}
	
	
	private class RefreshTask extends AsyncTask<Void, Void, String[]> {
		
		@Override
		protected String[] doInBackground(Void... params) {
			Log.i(TAG, "RefreshTask.doInBackground");
			//TODO action on "refresh" content : do some stuff here
			// simulate a 4sec. process :				//DEBUG
			try {										//DEBUG
				Thread.sleep(4000);						//DEBUG
			} catch (InterruptedException e) {			//DEBUG
				Log.e(TAG, "InterruptedException : ",e);//DEBUG
			}											//DEBUG
			
			// publish progress (call "onPostExecute" following method) :
			publishProgress();
			return null;
		}
		
		@Override
		protected void onPostExecute(String[] result) {
			Log.i(TAG, "RefreshTask.onPostExecute");
			//TODO update tablerows content
			prsvContent.onRefreshComplete();
			super.onPostExecute(result);
		}
	}
	
}
